import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { SegmentFormState, SegmentConfig, SegmentType } from './types';
import { updateSegment } from '@/services/project';
import { eventBus } from '@/utils/eventBus';

// 初始状态
const initialState: SegmentFormState = {
    currentSegment: null,
    config: {},
    loading: false,
    error: null,
};

// 创建 slice
const segmentFormSlice = createSlice({
    name: 'segmentForm',
    initialState,
    reducers: {
        // 设置当前片段
        setCurrentSegment: (state, action: PayloadAction<{
            draftId?: string;
            trackId?: string;
            segmentId?: string;
            type?: SegmentType;
            materialId?: string;
            start?: number;
            duration?: number;
        } | null>) => {
            state.currentSegment = action.payload;
            // 当设置新片段时，重置配置
            if (action.payload) {
                state.config = {};
            }
        },

        // 更新配置
        updateConfig: (state, action: PayloadAction<Partial<SegmentConfig>>) => {
            state.config = { ...state.config, ...action.payload };
        },

        // 设置加载状态
        setLoading: (state, action: PayloadAction<boolean>) => {
            state.loading = action.payload;
        },

        // 设置错误
        setError: (state, action: PayloadAction<string | null>) => {
            state.error = action.payload;
        },

        // 重置配置
        resetConfig: (state) => {
            state.config = {};
            state.error = null;
        },
    },
});

// 导出 actions
export const {
    setCurrentSegment,
    updateConfig,
    setLoading,
    setError,
    resetConfig,
} = segmentFormSlice.actions;

// 导出 reducer
export default segmentFormSlice.reducer;

// 异步 thunk：保存配置到后端
export const saveConfigToBackend = (config: SegmentConfig) => async (dispatch: any, getState: any) => {
    const state = getState();
    const { currentSegment } = state.segmentForm;

    if (!currentSegment || !currentSegment.draftId || !currentSegment.trackId || !currentSegment.segmentId) {
        dispatch(setError('缺少必要的片段信息'));
        return;
    }

    dispatch(setLoading(true));
    dispatch(setError(null));

    try {
        // 构建更新请求
        const updateRequest = {
            type: currentSegment.type || 'video',
            ...(currentSegment.materialId && { material_id: currentSegment.materialId }),
            start: currentSegment.start || 0,
            duration: currentSegment.duration || 0,
            segment_config: config,
        };

        console.log('保存配置到后端:', updateRequest);
        await updateSegment(
            currentSegment.draftId,
            currentSegment.trackId,
            currentSegment.segmentId,
            updateRequest
        );
        console.log('配置保存成功');
        
        // 发送事件通知 VideoPreview 重新获取数据
        eventBus.emit('segmentConfig:updated', {
            draftId: currentSegment.draftId,
            trackId: currentSegment.trackId,
            segmentId: currentSegment.segmentId,
            config: config
        });
    } catch (error) {
        console.error('保存配置失败:', error);
        dispatch(setError('保存配置失败'));
    } finally {
        dispatch(setLoading(false));
    }
};

// 选择器
export const selectCurrentSegment = (state: any) => state.segmentForm.currentSegment;
export const selectConfig = (state: any) => state.segmentForm.config;
export const selectLoading = (state: any) => state.segmentForm.loading;
export const selectError = (state: any) => state.segmentForm.error;
